package com.gongJiao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gongJiao.common.Result;
import com.gongJiao.entity.User;
import com.gongJiao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 登录控制器
 * @author Administrator
 */
@Controller
@RequestMapping("login")
public class LoginController {
    @Autowired
    UserService userService;
    /**
     * 进行登录
     * @return
     */
    @PostMapping("login")
    @ResponseBody
    public Result login(String username, String password, HttpSession session) {
        if(("").equals(username)){
            return Result.fail("用户名不能为空");
        }
        if(("").equals(password)){
            return Result.fail("密码不能为空");
        }
        User user=userService.getUser(username,password);
        if (user == null) {
            return Result.fail("用户名或密码不存在");
        }
        session.setAttribute("user",user);
        user.setPassword("");
        return Result.success("登录成功",user);
    }
    /**
     * 退出方法
     */
    @GetMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/";
    }
    /**
     * 切换账号方法
     */
    @RequestMapping("switchUser")
    public String switchUser(HttpSession session){
        session.removeAttribute("user");
        return "login";
    }
    /**
     * 注册方法
     */
    @PostMapping("register")
    @ResponseBody
    public Result register(String username,String password,String repeatPassword){
        if(("").equals(username)){
            return Result.fail("用户名不能为空");
        }
        if(("").equals(password)){
            return Result.fail("密码不能为空");
        }
        if(("").equals(repeatPassword)){
            return Result.fail("请再次输入密码");
        }
        if(!(password).equals(repeatPassword)){
            return Result.fail("两次密码必须一致");
        }
        Boolean flag=userService.getUserNameByUserName(username);
        if (flag) {
            User user=new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setNickname("游客");
            user.setCreateTime(new Date());
            user.setType(false);
            boolean save = userService.save(user);
            if (save) {
                return Result.success("注册成功");
            }else {
                return Result.fail("注册失败");
            }
        }else {
            return Result.fail("用户名以存在");
        }
    }
}
